package com.huilian.iotbox.admin.service.impl;

import com.huilian.iotbox.admin.dao.StatsMerchantDao;
import com.huilian.iotbox.admin.service.StatsMerchantService;
import com.huilian.iotbox.data.po.StatsMerchant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author 谢洛涛
 * @date 2021/9/28 11:31
 */
@Slf4j
@Service
public class StatsMerchantServiceImpl implements StatsMerchantService {

    @Autowired
    private StatsMerchantDao statsMerchantDao;

    @Override
    public void statsMerchantJob(String startTime, String endTime, String yesterday, String currentDateStr) throws Exception {
        List<StatsMerchant> statsStoreDetailList = statsMerchantDao.statsMerchant(startTime, endTime);
        for (StatsMerchant statsMerchant : statsStoreDetailList) {
            statsMerchant.setDateStr(yesterday);
            statsMerchantDao.insert(statsMerchant);
        }

        List<StatsMerchant> statsMerchantByActivity = statsMerchantDao.statsMerchantByActivity(startTime, endTime);
        for (StatsMerchant statsMerchant : statsMerchantByActivity) {
            StatsMerchant item = statsMerchantDao.findStatsMerchantByMchId(statsMerchant.getMerchantId(), yesterday);
            if (StringUtils.isEmpty(item)) {
                statsMerchant.setDateStr(yesterday);
                statsMerchantDao.insert(statsMerchant);
            } else {
                item.setRealTotalAmount(item.getRealTotalAmount().add(statsMerchant.getRealTotalAmount()));
                item.setSettlementMoney(item.getSettlementMoney().add(statsMerchant.getSettlementMoney()));
                item.setHandlingCharge(item.getHandlingCharge().add(statsMerchant.getHandlingCharge()));
                statsMerchantDao.update(item);
            }
        }
        //统计分账商户记录
        List<StatsMerchant> statsSplittingMerchantList = statsMerchantDao.statsSplittingMerchant(startTime, endTime);
        for (StatsMerchant statsMerchant : statsSplittingMerchantList) {
            statsMerchant.setDateStr(yesterday);
            statsMerchantDao.insert(statsMerchant);
        }
    }

    @Override
    public List<StatsMerchant> findStatsMerchantList(String dateStr) {
        return statsMerchantDao.findStatsMerchantList(dateStr);
    }
}
